import { handleApi } from '@packages/lib-api';
import Modal from '@packages/lib-modal';
import redirect from '@packages/lib-navigator/redirect';
import os from '@packages/lib-os';
import * as libUrl from '@packages/lib-url';

import openApp from './openApp';

let timer = 0;
function goNetUnlock(msg) {
    if (Date.now() - timer < 1000 || window.location.href.includes('net-unlock')) return;
    timer = Date.now();
    try {
        const { url } = JSON.parse(msg);
        redirect(libUrl.params(url, { _f: window.location.href }));
    } catch (e) {
        Modal.tips(msg);
    }
}

// 不同业务有不同的验证接口或验证方式，需要根据接口判断
const apiMap = new Map([
    // 修改身份信息
    // [
    //     '/v1.0/balance/check-can-update-user-name-code-l',
    //     {
    //         checkType: ['call'],
    //         callback: () => {
    //             WPT.showPage('/balance/setPassword/update');
    //         },
    //     },
    // ],
]);

// 将接口 url 替换成 /xxx/xxx/xxx 的形式
function decodeUrl(codedUrl) {
    return `/${codedUrl.split('?')[0].split('/').slice(-3).join('/')}`;
}

// 劫持 ajax的成功回调
$._ajax = $.ajax;
$.ajax = (option) => {
    const _option = option;
    const sucessCallback = option.success;
    // _dontInterceptThisAjax 业务中如果处理了绑定的逻辑，不需要在这里统一拦截，会带有这个参数，就会跳过
    const _dontInterceptThisAjax = option.data && option.data._dontInterceptThisAjax;
    _option.success = (data) => {
        // 900 用户未登录
        if (data && (data.code == '900' || (data.status && data.status.code == '900')) && !os.wechat) {
            WPT.login(option);
            // 908 用户需要绑定手机号
        } else if (data && data.code == '908' && !_dontInterceptThisAjax) {
            (function () {
                const currentOption = option;
                WPT.handleUserTelephone({
                    callback: () => {
                        $.ajax(currentOption);
                    },
                    ...apiMap.get(decodeUrl(option.url)),
                });
            })();
            // 909 用户需要验证手机号
        } else if (data && data.code == '909' && !_dontInterceptThisAjax) {
            (function () {
                const currentOption = option;
                WPT.handleUserTelephone({
                    callback: () => {
                        $.ajax(currentOption);
                    },
                    type: 'verify',
                    verifyTelephone: data.msg,
                    ...apiMap.get(decodeUrl(option.url)),
                });
            })();
            // 946 风险用户校验
        } else if (data && data.code == '946') {
            const msgObj = JSON.parse(data.msg);
            (function () {
                const currentOption = option;
                WPT.handleUserTelephone({
                    callback: () => {
                        msgObj.isContinue && $.ajax(currentOption);
                    },
                    sendCodeUrl: handleApi('/v1.0/riskverify/send-telephone-call-l'),
                    codeVerifyUrl: handleApi('/v1.0/riskverify/verify-l'),
                    riskverify: true,
                    type: 'verify',
                    checkType: msgObj.verifyType === 'call' ? ['call'] : ['sms', 'call'],
                    verifyTelephone: msgObj.telephone,
                });
            })();
        } else if (data && data.code == '444') {
            goNetUnlock(data.msg);
        } else if (data && data.code == '301' && data.msg.includes('/webApp/accountCheck')) {
            // 301 跳转 如果是账号持有人校验则需要拼接参数
            WPT.showPage(`${data.msg}&checkFromUrl=${window.location.pathname}`);
        } else {
            if (data && typeof data === 'object') {
                data.fromLogin = _option.fromLogin;
                os.device === 'native' && (data.fromLogin = 1);
            }
            sucessCallback && sucessCallback(data);
        }
    };
    return $._ajax(_option);
};

// 微信版本升级提醒
function noticeWeChatVer() {
    const weChatInfo = navigator.userAgent.match(/MicroMessenger\/([\d.]+)/i);
    if (weChatInfo && weChatInfo[1] < '6.0.2') {
        WPT.Modal.alert('您的微信版本太老了，不能发布拍品，请升级至6.1以上版本！');
        return true;
    }

    if (!weChatInfo) {
        WPT.Modal.alert('PC端上传照片功能正在开发中，请至手机微信端进行此操作！');
        return true;
    }
    return false;
}

export { redirect, noticeWeChatVer, openApp };
